<template>
  <div class="userBox">
    <!-- <h1>User组件</h1> -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>活动详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row type="flex">
        <el-col :span="8">
          <div class="grid-content bg-purple title" style="text-align: left">
            <el-input
              clearable
              placeholder="请输入内容"
              v-model.trim="params.query"
              class="input-with-select"
              @keydown.native.enter="getSearchUsers"
              @clear="getSearchUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getSearchUsers"
              ></el-button>
            </el-input>
          </div>
        </el-col>

        <el-col :span="8">
          <el-row type="flex">
            <el-col :span="2"></el-col>
            <el-col :span="20">
              <el-button type="primary" @click="dialogFormVisibleAdd = true"
                >添加用户</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-table v-loading = "isLoading" :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50" label="#"></el-table-column>

        <el-table-column prop="username" label="用户" width="">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width=""> </el-table-column>
        <el-table-column prop="mobile" label="电话" width=""> </el-table-column>
        <el-table-column prop="role_name" label="角色" width="">
        </el-table-column>
        <el-table-column label="状态" width="">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="173">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="
                handleEdit(scope.$index, scope.row);
                dialogFormVisibleEdit = true;
              "
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-setting"
                @click="AssignUser(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage"
    >
    </el-pagination>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="用户名称"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisibleEdit">
      <el-form :model="currentEdit" :rules="rules" ref="formEdit">
        <el-form-item
          label="用户名称"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="currentEdit.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="currentEdit.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="currentEdit.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限 角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRole">
      <el-form :model="AssignFrom">
        <el-form-item label="当前的用户:" :label-width="formLabelWidth">
          {{AssignFrom.username}}
        </el-form-item>
        <el-form-item label="当前的角色:" :label-width="formLabelWidth">
          {{AssignFrom.role_name}}
        </el-form-item>
        <el-form-item label="分配新角色:" :label-width="formLabelWidth">
          <el-select v-model="roleId" placeholder="请选择" >
            <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.id"></el-option>
            <!-- <el-option label="区域二" value="beijing"></el-option> -->
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleRole = false">取 消</el-button>
        <el-button type="primary" @click="AssignUserSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  getChangeUserState,
  getAddUsers,
  getDeleteUser,
  getEditUser,
  getRoleList,
  getAssignUser,

} from "../../api/index";

export default {
  data() {
    // 验证手机号
    var validateMobile = (rule, value, callback) => {
      let regMobile = /^[1]([3-9])[0-9]{9}$/;

      if (!regMobile.test(value)) {
        callback(new Error("手机号码格式错误"));
      } else {
        callback();
      }
    };
    // 验证邮箱
    var validateEmail = (rule, value, callback) => {
      let regEmail = /^([A-z0-9]{6,18})(\w|\-)+@[A-z0-9]+\.([A-z]{2,3})$/;

      if (!regEmail.test(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };

    return {
      isLoading: true,
      tableData: [
        // {
        //   id: 25,
        //   username: "tige117",
        //   mobile: "18616358651",
        //   type: 1,
        //   email: "tige112@163.com",
        //   create_time: "2017-11-09T20:36:26.000Z",
        //   mg_state: true, // 当前用户的状态
        //   role_name: "炒鸡管理员",
        // },
      ],
      totalpage: 0, //总页数
      params: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      dialogFormVisibleAdd: false,
      dialogFormVisibleEdit: false,
      dialogFormVisibleRole: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "120px",
      // 验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },

      // 当前编辑的值
      currentEdit: {
        username: "",
        email: "",
        mobile: "",
      },
      // 分配角色
      // 存储分配角色时获取的用户信息
      AssignFrom: {},
      // 角色列表
      roleList: [],
      // 角色ID
      roleId: "",
    };
  },

  created() {
    this.getUsersList();
  },
  methods: {
    async getUsersList() {
      let {
        data: { users, pagenum, total },
      } = await getUsers(this.params);

      this.isLoading = false
      this.tableData = users;
      this.params.pagenum = pagenum;
      this.totalpage = total;
    },
    // 搜索功能
    getSearchUsers() {
      this.getUsersList();
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.pagenum = val;
      this.getUsersList();
    },
    // 改变状态
    async changeUserState(data) {
      let res = await getChangeUserState({ id: data.id, type: data.mg_state });
      // console.log(res)
      let {
        meta: { msg, status },
      } = res;
      if (status == 200) {
        this.$message.success(msg);
        this.getUsersList();
      }
    },
    // 添加用户
    async addUsers() {
      // 表单验证
      let result = await this.$refs["form"].validate().catch(() => {});
      // console.log(result);
      if (!result) return false;

      // 2. 验证成功发送请求
      let res = await getAddUsers(this.form);
      // console.log(res);
      let {
        meta: { msg, status },
      } = res; //解构

      if (status == 201) {
        this.$message.success(msg);
        // 关闭弹框
        this.dialogFormVisibleAdd = false;
        this.getUsersList();
        return;
      } else {
        // 用户名重复
        this.$message.warning(msg);
      }
    },
    // 修改用户
    handleEdit(index, row) {
      console.log(index, row);
      this.currentEdit = row;

      // let res = await getEditUser(row)
      console.log(this.currentEdit);
    },
    // 确认修改
    async editUsers() {
      let result = await this.$refs["formEdit"].validate().catch(() => {});
      console.log(result);
      if (!result) return false;

      let res = await getEditUser(this.currentEdit);
      console.log(res);
      let {
        meta: { msg, status },
      } = res;

      if (status == 200) {
        this.$message.success(msg);
        this.dialogFormVisibleEdit = false;
        this.getUsersList();
      } else {
        this.$message.warning(msg);
      }
    },
    // 取消修改
    cancelEdit() {
      this.dialogFormVisibleEdit = false;
      this.getUsersList();
    },
    // 删除用户
    async handleDelete(index, row) {
      try {
        let res = await this.$confirm("是否删除该用户？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // console.log(res)
        if (res == "confirm") {
          // this.$message.success("成功删除用户");
          let res = await getDeleteUser(row.id);
          let {
            meta: { msg, status },
          } = res;
          if (status == 200) {
            this.$message.success(msg);
            this.getUsersList();
          } else {
            this.$message.warning(msg);
          }
        }
      } catch {
        this.$message.info("取消删除");
      }
    },
    // 分配角色
    async AssignUser(row){
      this.dialogFormVisibleRole = true
      // console.log(row)
      // 存储当前角色信息
      this.AssignFrom = row
      // 获取角色列表
      let res = await getRoleList()
      // console.log(res)
      let {data} = res
      this.roleList = data

    },
    async AssignUserSubmit(){
        let uid = this.AssignFrom.id
        let rid = this.roleId
        let res = await getAssignUser({id: uid,rid:rid})
        let {meta: {msg,status}} = res
        if(status != 200) return this.$message.error(msg)
        this.$message.success(msg)
        this.getUsersList()
        this.dialogFormVisibleRole = false

        console.log(res)
    }
  },
};
</script>

<style lang="less" scoped>

</style>